const koa = require("koa");
const Router = require("koa-router");
const router = new Router();
const path = require("path");
const multer = require("@koa/multer");
const cors = require("@koa/cors");
const onerror = require("koa-onerror");
const app = new koa();

app.use(cors()); // 允许所有跨域请求
// 设置文件存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/image"); // 指定上传的文件存储路径
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    ); // 生成唯一文件名
  },
});

// 初始化multer
const upload = multer({
  storage: storage,
  fileFilter,
  limits: {
    fileSize: 1 * 1024 * 1024, // 限制单个文件大小为 1KB
    files: 5, // 限制上传文件数量为 5
  },
});

router.post("/upload", upload.single("file"), async (ctx) => {
  ctx.body = {
    code: 200,
    msg: "上传成功",
    data: ctx.file,
  };
});
// 处理多个文件上传
// router.post("/upload", upload.array("file", 5), async (ctx) => {
//   console.log(ctx.files);

//   ctx.body = {
//     code: 200,
//     msg: "上传成功",
//     data: ctx.files,
//   };
// });
function fileFilter(req, file, cb) {
  if (file.originalname.includes("png")) {
    cb(new Error("仅允许上传jpg图片文件！"), false); // 不允许上传，传递错误信息
  } else {
    cb(null, true);
  }
}
app.on("error", (err, ctx) => {
  console.log(666, err);

  ctx.body = {
    code: 500,
    msg: err,
  };
});

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
